import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import PublicActivitiesView from '../views/PublicActivitiesView.vue';
import PublicActivityDetailView from '../views/PublicActivityDetailView.vue';
import ActivityManagementView from '../views/ActivityManagementView.vue';
import { isAuthenticated, isAdmin } from '../utils/auth'; // 引入验证函数

Vue.use(VueRouter);

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities/:id',
    name: 'public-activity-detail',
    component: PublicActivityDetailView,
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: { requiresAuth: true, requiresAdmin: true }
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    // 如果需要认证但未登录，重定向到登录页
    next('/login');
  } else if (to.meta.requiresAdmin && !isAdmin()) {
    // 如果需要管理员权限但不是管理员，提示无权限并返回首页
    alert('No permission');
    next('/');
  } else {
    // 否则继续导航
    next();
  }
});

export default router;